name: Deploy by ssh

env:
  SSH_USERNAME: "ubuntu"
  SSH_HOST_NAME: "ec2-52-29-207-95.eu-central-1.compute.amazonaws.com"
  SSH_PORT: "22"

on:
  push:
    branches:
      - release

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v3

      - name: Change directory permitions
        uses: appleboy/ssh-action@master
        with:
          host: ${{ env.SSH_HOST_NAME }}
          username: ${{ env.SSH_USERNAME }}
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          port: ${{ env.SSH_PORT }}
          script: |
            [[ -f /home/${{ env.SSH_USERNAME }}/Crystall/ ]] \
            && sudo chmod -R 777 /home/${{ env.SSH_USERNAME }}/Crystall/ \
            || echo "/home/${{ env.SSH_USERNAME }}/Crystall/ not found"
            
      - name: Refresh content
        uses: webfactory/ssh-agent@v0.5.4
        with:
          ssh-private-key: ${{ secrets.DEPLOY_SSH_KEY }}
      - name: Sync Repository via SSH
        run: |
          rsync -e "ssh -i $HOME/.ssh/key -o StrictHostKeyChecking=no" --archive --compress --delete \
          . ${{ env.SSH_USERNAME }}@${{ env.SSH_HOST_NAME }}:Crystall

      - name: Change directory permitions again
        uses: appleboy/ssh-action@master
        with:
          host: ${{ env.SSH_HOST_NAME }}
          username: ${{ env.SSH_USERNAME }}
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          port: ${{ env.SSH_PORT }}
          script: |
            sudo chmod -R 777 /home/${{ env.SSH_USERNAME }}/Crystall/devops \
            && ls -l /home/${{ env.SSH_USERNAME }}/Crystall/devops

      - name: Check docker and docker-compose
        uses: appleboy/ssh-action@master
        with:
          host: ${{ env.SSH_HOST_NAME }}
          username: ${{ env.SSH_USERNAME }}
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          port: ${{ env.SSH_PORT }}
          script: |
             /home/${{ env.SSH_USERNAME }}/Crystall/devops/check_docker.sh || \
             /home/${{ env.SSH_USERNAME }}/Crystall/devops/install_docker_docker-compose.sh

      - name: Stop docker conteiners and clean docker images
        uses: appleboy/ssh-action@master
        with:
          host: ${{ env.SSH_HOST_NAME }}
          username: ${{ env.SSH_USERNAME }}
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          port: ${{ env.SSH_PORT }}
          script: |
            sudo docker stop $(docker ps -aq) && \
            sudo docker system prune --all --force \
            || echo "No docker conteiners are running"

      - name: Start docker compose
        uses: appleboy/ssh-action@master
        with:
          host: ${{ env.SSH_HOST_NAME }}
          username: ${{ env.SSH_USERNAME }}
          key: ${{ secrets.DEPLOY_SSH_KEY }}
          port: ${{ env.SSH_PORT }}
          script: |
            sudo docker compose -f /home/${{ env.SSH_USERNAME }}/Crystall/docker-compose.yml up -d

